<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Dinghuo extends Model
{

    

    

    // 表名
    protected $name = 'dinghuo';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'dingtime_text',
        'good_json_text',
        'pay_status_text'
    ];
    public function getGoodJsonTextAttr($value, $data)
    {
        if($data){
            $destination_json_text = json_decode($data['good_json'],true);
            return $destination_json_text;
        }
    }
    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $good_json = $row->good_json;
            $good_array = json_decode($good_json,true);
            $createtime = time();
            $insertall = [];
            // halt($good_array);
            foreach ($good_array as $key => $value) {
                $if_exist = Db::name('dinggood')->where(['name'=>$value['name']])->find();
                if($if_exist){
                    Db::name('dinggood')->where(['name'=>$value['name']])->setInc('sum_need_num',$value['ding_num']);
                    Db::name('dinggood')->where(['name'=>$value['name']])->setInc('wei_fahuo_num',$value['weifahuo']);
                    Db::name('dinggood')->where(['name'=>$value['name']])->setInc('yifahuo_num',$value['yifahuo']);
                }else{
                    $insertall['createtime'] = $createtime;
                    $insertall['name'] = $value['name'];
                    $insertall['sum_need_num'] = $value['ding_num'];
                    $insertall['wei_fahuo_num'] = $value['weifahuo'];
                    $insertall['yifahuo_num'] = $value['yifahuo'];
                    // halt($insertall);
                    $res = Db::name('dinggood')->insert($insertall);
                    // halt($res);
                }
                

            }
        });
    }

    
    public function getPayStatusList()
    {
        return ['10' => __('Pay_status 10'), '20' => __('Pay_status 20'), '30' => __('Pay_status 30')];
    }

    public function getDingtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['dingtime']) ? $data['dingtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setDingtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

            public function admin()
    {
        return $this->belongsTo('admin', 'user_id')->bind('nickname');
    }

}
